package com.elecbook.base.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * description 此处配置的序列化器会直接作用到spring中用于序列化的ObjectMapper
 * 当然，在这个文件的同级目录下有我编写的CustomObjectMapperConfig.java,这个文件给出了直接自定义objectMapper的方法
 * 当然，还是建议单独配置Jackson2ObjectMapperBuilderCustomizer，这个使用的多一些
 * -
 * 错误汇报于2024/10/28，发现序列化错误的问题，此序列化错误的问题出现在learning模块下的测试类FeignClientTest的调用
 * 在调用的时刻，测试文件夹中，spring的启动类位置是错误的，导致了无法扫描到base依赖中的一个Component注解JacksonConfig的component
 * -
 * 原因是：spring的启动类位置是错误的，建议以后使用启动类的时候，使用classes的方式进行指定测试类的启动类，方便查看
 * 测试类所在的包位置，减少时间的浪费
 * - @SpringBootTest(classes = LearningApplication.class)
 *
 * @author zken
 * CreateDate 2024/10/28 20:57:07
 */
@Configuration
public class JacksonConfig {
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    //    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            // localDateTime
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
            //LocalDate
            builder.serializerByType(LocalDate.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
            builder.deserializerByType(LocalDate.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
            //LocalTime
            builder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
            builder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        };
    }
}